package com.dousb.cloudlibrary.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dousb.cloudlibrary.mapper.AnnouncementMapper;
import com.dousb.cloudlibrary.model.entity.Announcement;
import com.dousb.cloudlibrary.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/ws")
@Slf4j
public class WebSocketController {
    @Resource
    private WebSocketServer webSocketServer;

    @Resource
    private AnnouncementMapper announcementMapper;

    @GetMapping("index")
    public ResponseEntity<String> index() {
        return ResponseEntity.ok("请求成功");
    }

    @GetMapping("page")
    public ModelAndView page() {
        return new ModelAndView("websocket");
    }

    /**
     * 单发信息
     *
     * @param message
     * @param toUserId
     * @return
     * @throws IOException
     */
    @PostMapping("/push/{toUserId}")
    public ResponseEntity<String> pushToWeb(String message, @PathVariable String toUserId) throws IOException {
        WebSocketServer.sendInfo(message, toUserId);
        return ResponseEntity.ok("信息发送成功");
    }

    /**
     * 发布公告
     */
    @PostMapping("/announcement/publish")
    public ResponseEntity<String> publishAnnouncementAll(@RequestParam String content) {
        if (content == null || content.trim().isEmpty()) {
            return ResponseEntity.ok("公告内容不能为空");
        }

        // 1. 保存公告到数据库（供离线用户后续读取）
        Announcement announcement = new Announcement();
        announcement.setContent(content);
        announcement.setCreateTime(new Date());
        announcementMapper.insert(announcement);

        // 2. 广播给所有在线用户
        WebSocketServer.broadcastAnnouncement(content);

        return ResponseEntity.ok("公告发布成功，已存储并发送给在线用户");
    }

    /**
     * 查询所有公告（供用户上线时获取历史公告）
     */
    @GetMapping("/api/announcement/all")
    public List<Announcement> getAllAnnouncements() {
        return announcementMapper.selectList(new QueryWrapper<Announcement>()
                .orderByDesc("publishTime"));
    }
}
